<template>
  <div class="line-chart-container w-full h-full flex flex-col">
    <!-- 图表标题 -->
    <div v-if="component.title" class="chart-title mb-2" :style="{ textAlign: 'center' }">
      <h3 :style="{ fontSize: component.titleFontSize || '16px', color: component.titleColor || '#333' }">
        {{ component.title }}
      </h3>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-message text-red-500 text-center py-4">
      {{ errorMessage }}
    </div>
    
    <!-- 加载状态 -->
    <div v-if="isLoading && !errorMessage" class="loading-state flex items-center justify-center flex-1">
      <div class="loader animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
      <span class="ml-2 text-gray-600">加载中...</span>
    </div>
    
    <!-- 图表容器 - 确保有明确尺寸 -->
    <div v-if="!errorMessage && !isLoading" class="chart-content flex-1 relative w-full h-full min-h-[400px]">
      <VueUiXy
        :config="config"
        :dataset="dataset"
        class="w-full h-full"
        @error="handleChartError"
      />
    </div>
  </div>
</template>

<script>
import { defineProps, ref, watch, onMounted, onUnmounted, nextTick } from 'vue';
import { VueUiXy } from "vue-data-ui";
import "vue-data-ui/style.css";

export default {
  name: 'LineChart',
  components: {
    VueUiXy
  },
  props: {
    component: {
      type: Object,
      required: true,
      description: '折线图组件配置'
    },
    isPreview: {
      type: Boolean,
      default: false,
      description: '是否预览模式'
    }
  },
  setup(props) {
    // 状态管理
    const isLoading = ref(false);
    const errorMessage = ref('');
    
    // 配置响应式化 - 更完整的默认配置
    const config = ref({
      debug: false,
      loading: false,
      responsive: true,
      theme: 'light',
      customPalette: props.component.colors || ['#52c41a', '#faad14', '#1890ff', '#722ed1', '#ff4d4f'],
      style: {
        fontFamily: 'system-ui, sans-serif',
        chart: {
          backgroundColor: props.component.bgColor || '#FFFFFF',
          color: '#1A1A1A',
          animation: {
            use: true,
            speed: 3,
            acceleration: 1
          },
          padding: {
            top: 30,
            right: 30,
            bottom: 50,  // 增加底部内边距防止标签被截断
            left: 50
          },
          axis: {
            x: {
              show: true,
              type: 'category',
              label: {
                show: true,
                rotate: props.component.xAxisRotate || 0,
                fontSize: 12,
                color: '#666'
              },
              title: {
                show: !!props.component.xAxisTitle,
                text: props.component.xAxisTitle || '',
                fontSize: 14,
                color: '#666',
                margin: 15
              },
              line: {
                show: true,
                color: '#ddd'
              }
            },
            y: {
              show: true,
              type: 'value',
              label: {
                show: true,
                fontSize: 12,
                color: '#666'
              },
              title: {
                show: !!props.component.yAxisTitle,
                text: props.component.yAxisTitle || '',
                fontSize: 14,
                color: '#666',
                margin: 15
              },
              line: {
                show: true,
                color: '#ddd'
              },
              grid: {
                show: true,
                color: '#f5f5f5'
              }
            }
          },
          lines: {
            show: true,
            thickness: 2,
            smooth: props.component.smooth || false,
            fill: props.component.areaFill || false,
            fillOpacity: 0.2
          },
          points: {
            show: true,
            size: 4,
            borderWidth: 2,
            hover: {
              size: 6,
              active: true
            }
          },
          legend: {
            show: true,
            position: props.component.legendPosition || 'top',
            align: 'center',
            fontSize: 12,
            margin: 10
          },
          tooltip: {
            show: true,
            backgroundColor: 'rgba(0, 0, 0, 0.7)',
            color: '#fff',
            padding: 10,
            borderRadius: 4
          }
        },
        title: {
          text: props.component.title || '',
          color: props.component.titleColor || '#1A1A1A',
          fontSize: props.component.titleFontSize || 20,
          bold: true,
          textAlign: 'center',
          margin: 10
        }
      },
      userOptions: {
        show: !props.isPreview,
        buttons: {
          pdf: false,
          img: !props.isPreview,
          fullscreen: true
        }
      }
    });

    // 数据响应式化 - 确保有默认数据
    const dataset = ref({
      labels: props.component.labels || ['1月', '2月', '3月', '4月', '5月', '6月'],
      series: props.component.series || [
        {
          name: '默认数据',
          data: [12, 34, 22, 56, 45, 67],
          color: '#1890ff'
        }
      ]
    });

    // 定时器变量
    let refreshTimer = null;

    // 处理图表错误
    const handleChartError = (err) => {
      console.error('图表渲染错误:', err);
      errorMessage.value = '图表加载失败，请检查配置';
    };

    // 验证数据格式
    const validateData = (data) => {
      if (!data || typeof data !== 'object') {
        return '数据格式不正确';
      }
      
      if (!Array.isArray(data.labels) || data.labels.length === 0) {
        return '缺少有效的标签数据';
      }
      
      if (!Array.isArray(data.series) || data.series.length === 0) {
        return '缺少有效的系列数据';
      }
      
      // 检查每个系列的数据长度是否与标签匹配
      for (const serie of data.series) {
        if (!serie.data || !Array.isArray(serie.data) || serie.data.length !== data.labels.length) {
          return '系列数据长度与标签不匹配';
        }
      }
      
      return null;
    };

    // 从API加载数据
    const loadDataFromApi = async () => {
      if (!props.component.apiUrl) return;
      
      isLoading.value = true;
      errorMessage.value = '';
      
      try {
        const response = await fetch(props.component.apiUrl);
        
        if (!response.ok) {
          throw new Error(`HTTP错误: ${response.status}`);
        }
        
        const data = await response.json();
        const validationError = validateData(data);
        
        if (validationError) {
          throw new Error(validationError);
        }
        
        // 更新图表数据
        if (data.labels) {
          dataset.value.labels = data.labels;
        }
        
        if (data.series) {
          dataset.value.series = data.series;
        }
        
        // 触发重绘
        await nextTick();
      } catch (error) {
        console.error('加载折线图数据失败:', error);
        errorMessage.value = `数据加载失败: ${error.message}`;
        // 保持显示最后可用的数据
      } finally {
        isLoading.value = false;
      }
    };

    // 设置定时刷新
    const setupRefreshTimer = () => {
      if (refreshTimer) {
        clearInterval(refreshTimer);
      }
      
      if (props.component.dataSourceType === 'api' && props.component.refreshInterval > 0) {
        refreshTimer = setInterval(loadDataFromApi, props.component.refreshInterval * 1000);
      }
    };

    // 初始化
    onMounted(() => {
      // 确保DOM渲染完成后再加载数据
      nextTick().then(() => {
        if (props.component.dataSourceType === 'api') {
          loadDataFromApi();
          setupRefreshTimer();
        } else {
          // 验证本地数据
          const validationError = validateData(dataset.value);
          if (validationError) {
            errorMessage.value = validationError;
          }
        }
      });
    });

    // 监听组件属性变化
    watch(
      () => props.component,
      (newVal) => {
        // 更新配置
        config.value.style.chart.title.text = newVal.title || '';
        config.value.style.chart.title.color = newVal.titleColor || '#1A1A1A';
        config.value.style.chart.backgroundColor = newVal.bgColor || '#FFFFFF';
        
        // 更新坐标轴
        if (newVal.xAxisTitle) {
          config.value.style.chart.axis.x.title.text = newVal.xAxisTitle;
          config.value.style.chart.axis.x.title.show = true;
        }
        
        if (newVal.yAxisTitle) {
          config.value.style.chart.axis.y.title.text = newVal.yAxisTitle;
          config.value.style.chart.axis.y.title.show = true;
        }
        
        // 更新图例位置
        if (newVal.legendPosition) {
          config.value.style.chart.legend.position = newVal.legendPosition;
        }
        
        // 更新数据
        if (newVal.labels) {
          dataset.value.labels = newVal.labels;
        }
        
        if (newVal.series) {
          dataset.value.series = newVal.series;
        }
        
        // 重新验证数据
        const validationError = validateData(dataset.value);
        errorMessage.value = validationError || '';
        
        // 数据源变化时重新加载
        if (newVal.dataSourceType === 'api') {
          loadDataFromApi();
          setupRefreshTimer();
        }
      },
      { deep: true }
    );

    // 清理
    onUnmounted(() => {
      if (refreshTimer) {
        clearInterval(refreshTimer);
      }
    });

    return {
      config,
      dataset,
      isLoading,
      errorMessage,
      handleChartError
    };
  }
};
</script>

<style scoped>
.line-chart-container {
  padding: 16px;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  min-height: 400px; /* 确保容器有足够高度 */
}

.chart-content {
  width: 100%;
  height: 100%;
}

/* 加载动画 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.animate-spin {
  animation: spin 1s linear infinite;
}
</style>
